package org.ziegler.log.analysis.resultHandler;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import org.ziegler.log.analysis.LogCore;
import org.ziegler.log.analysis.core.SplitColumn;

public class LastErrResultHandler implements ResultHandler {

    /** 每个Error只有日期最近的一条 */
    private final Map<String, SplitColumn> distinctError = new HashMap<>();

    @Override
    public void addResult(SplitColumn splitColumn) {
        if (StringUtils.isNotBlank(splitColumn.getKey())) {
            // 只保存不重复的数据
            distinctError.merge(splitColumn.getKey(), splitColumn, (oldValue, newValue) -> {
                if (newValue.getDateTime().isAfter(oldValue.getDateTime())) {
                    // 新Error覆盖旧Error
                    return newValue;
                } else {
                    return oldValue;
                }
            });
        }
    }

    @Override
    public void output() {
        LogCore.info("下面记录总数：" + distinctError.size());
        distinctError.forEach((key, value) -> {
            //
            LogCore.log(value.getStr());
        });
    }

}
